//
//  View_ToCamera.swift
//  example10003
//
//  Created by kazarus on 4/15/16.
//  Copyright © 2016 kazarus. All rights reserved.
//

import UIKit
import AVFoundation

protocol KzViewToCameraDelegate {
    
    func onToCameraComplete(_ sender:UIViewController,value:[String])
    func onToCameraCanceled()
    
}

class TViewToCamera: UIViewController,AVCaptureMetadataOutputObjectsDelegate {

    
    //MARK:数据声明
    var metaData : [String]=[];
    var delegate : KzViewToCameraDelegate?
    var alrtView : UIAlertController!
    
    //MARK:扫描声明
    var scanRectView:UIView!
    var device:AVCaptureDevice!
    var input:AVCaptureDeviceInput!
    var output:AVCaptureMetadataOutput!
    var session:AVCaptureSession!
    var preview:AVCaptureVideoPreviewLayer!
    
    //MARK:默认周期
    override func viewDidLoad() {
        super.viewDidLoad()
        
        callCamera();
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    //MARK:开始扫描
    func callCamera(){
        do{
            self.device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
            
            self.input = try AVCaptureDeviceInput(device: device)
            
            self.output = AVCaptureMetadataOutput()
            output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            
            self.session = AVCaptureSession()
            if UIScreen.main.bounds.size.height<500 {
                self.session.sessionPreset = AVCaptureSessionPreset640x480
            }else{
                self.session.sessionPreset = AVCaptureSessionPresetHigh
            }
            
            self.session.addInput(self.input)
            self.session.addOutput(self.output)
            
            //self.output.metadataObjectTypes=[AVMetadataObjectTypeQRCode]
            
            
            self.output.metadataObjectTypes = [AVMetadataObjectTypeEAN13Code,
                                               AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code,
                                               AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode93Code]
            
            
            //计算中间可探测区域
            let windowSize:CGSize = UIScreen.main.bounds.size;
            let scanSize:CGSize = CGSize(width: windowSize.width*3/4,
                                             height: windowSize.width*3/4);
            var scanRect:CGRect = CGRect(x: (windowSize.width-scanSize.width)/2,
                                             y: (windowSize.height-scanSize.height)/2, width: scanSize.width, height: scanSize.height);
            //计算rectOfInterest 注意x,y交换位置
            scanRect = CGRect(x: scanRect.origin.y/windowSize.height,
                                  y: scanRect.origin.x/windowSize.width,
                                  width: scanRect.size.height/windowSize.height,
                                  height: scanRect.size.width/windowSize.width);
            //设置可探测区域
            self.output.rectOfInterest = scanRect
            
            self.preview = AVCaptureVideoPreviewLayer(session:self.session)
            self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill
            self.preview.frame = UIScreen.main.bounds
            self.view.layer.insertSublayer(self.preview, at:0)
            
            //添加中间的探测区域绿框
            self.scanRectView = UIView();
            self.view.addSubview(self.scanRectView)
            self.scanRectView.frame = CGRect(x: 0, y: 0, width: scanSize.width, height: scanSize.height);
            self.scanRectView.center = CGPoint(
                x: UIScreen.main.bounds.midX,
                y: UIScreen.main.bounds.midY);
            self.scanRectView.layer.borderColor = UIColor.green.cgColor
            self.scanRectView.layer.borderWidth = 1;
            
            //开始捕获
            self.session.startRunning()
            
            //放大
            /*
             do {
             try self.device!.lockForConfiguration()
             } catch _ {
             NSLog("Error: lockForConfiguration.");
             }
             self.device!.videoZoomFactor = 1.5
             self.device!.unlockForConfiguration()
             */
            
        }catch _ as NSError{
            alrtView = UIAlertController(title: "提示", message: "请在iPhone的\"设置-隐私-相机\"选项中,允许本程序访问您的相机", preferredStyle: .alert)
            let actionOk = UIAlertAction(title: "确定", style: .cancel,handler: nil)
            alrtView.addAction(actionOk)
            self.present(alrtView, animated: true, completion: nil)
        }
    }
    
    //MARK:扫描捕获
    private func captureOutput(_ captureOutput: AVCaptureOutput!,
                       didOutputMetadataObjects metadataObjects: [AnyObject]!,
                       from connection: AVCaptureConnection!) {
        
        var stringValue:String?
        if metadataObjects.count > 0 {
            let metadataObject = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
            stringValue = metadataObject.stringValue
            
            if stringValue != nil{
                
                self.metaData.append(stringValue!)
                self.session.stopRunning()
            }
        }
        //#self.session.stopRunning()
        
        alrtView = UIAlertController(title: "提示", message: "已扫:\(self.metaData.count)", preferredStyle: .actionSheet)
    
        let actionCanceled = UIAlertAction(title: "放弃扫描", style: UIAlertActionStyle.cancel) { (paramActoin:UIAlertAction!) -> Void in
            print("取消扫描")
            
            if ((self.delegate) != nil) {
                self.delegate?.onToCameraCanceled()
            }
            _ = self.navigationController?.popToRootViewController(animated: true)
            
        }
        alrtView.addAction(actionCanceled);
        
        let actionContinue = UIAlertAction(title: "继续扫描", style: .default) { (paramActoin:UIAlertAction!) -> Void in
            print("继续扫描")
            self.session.startRunning();
        }
        alrtView.addAction(actionContinue);
        
        let actionComplete = UIAlertAction(title: "结束扫描", style: .default) { (paramActoin:UIAlertAction!) -> Void in
            print("结束扫描")
            self.session.stopRunning()
            
            if ((self.delegate) != nil) {
                self.delegate?.onToCameraComplete(self, value: self.metaData)
            }
           _ = self.navigationController?.popToRootViewController(animated: true)
            
        }
        alrtView.addAction(actionComplete);
        
        self.present(alrtView, animated: true, completion: nil)
    }
}
